package com.my.geojson.mybatis.config.jts.converter;

import com.google.common.collect.Maps;
import org.locationtech.jts.geom.Geometry;

import java.sql.SQLException;
import java.util.Map;

/**
 * Converter JTS Geometry to/from byte array.
 * Inspired by
 * <a
 * href="http://www.dev-garden.org/2011/11/27/loading-mysql-spatial-data-with-jdbc-and-jts-wkbreader/">Loading
 * MySQL Spatial Data with JDBC and JTS WKBReader</a>. Using Object instead
 * of byte[] because of codegen.
 *
 * @ClassName GeometryConverter
 * @Date 2022-04-15 0:32
 * @Version 1.0
 */
public class GenericGeometryConverter {

    private Map<String, GeometryConverter> converters = Maps.newHashMapWithExpectedSize(3);

    public GenericGeometryConverter() {
        PgGeometryConverter pgGeometryConverter = new PgGeometryConverter();
        MysqlGeometryConverter mysqlGeometryConverter = new MysqlGeometryConverter();
        SqlServerGeometryConverter sqlServerGeometryConverter = new SqlServerGeometryConverter();
        converters.put(pgGeometryConverter.getDatabaseProductName(), pgGeometryConverter);
        converters.put(mysqlGeometryConverter.getDatabaseProductName(), mysqlGeometryConverter);
        converters.put(sqlServerGeometryConverter.getDatabaseProductName(), sqlServerGeometryConverter);
    }

    /**
     * Convert byte array containing SRID + WKB Geometry into Geometry object
     */
    public Geometry from(Object databaseObject, String databaseProductName) throws SQLException {
        GeometryConverter geometryConverter = converters.get(databaseProductName);
        if (null == geometryConverter) {
            throw new SQLException("未配置[" + databaseProductName + "]数据库geometry类型对应geometryConverter转换器实现");
        }
        return geometryConverter.from(databaseObject);
    }

    /**
     * Convert Geometry object into byte array containing SRID + WKB Geometry
     */
    public Object to(Geometry geometry, String databaseProductName) throws SQLException {
        GeometryConverter geometryConverter = converters.get(databaseProductName);
        if (null == geometryConverter) {
            throw new SQLException("未配置[" + databaseProductName + "]数据库geometry类型对应geometryConverter转换器实现");
        }
        return geometryConverter.to(geometry);
    }


}
